<template>
  <div class="sellPoints">
    <el-form ref="ruleForm" :model="formDate" size="mini" :inline="true" label-width="120px" label-position="right" :validate-on-rule-change="false">
      <div v-for="(sellPoint,index) in formDate.sellPoints" :key="index" class="goodsList">
        <h2>
          <span>UPC：{{ sellPoint.upc }}</span>
          <span>商品名称：{{ sellPoint.skuName }}</span>
          <el-button v-if="index==0&&!isDisabled" type="text" size="mini" @click="exportExcel">导出到Excel维护</el-button>
          <el-upload
            v-if="index==0&&!isDisabled"
            style="margin-left:10px"
            class="upload-demo"
            :auto-upload="false"
            action="#"
            :show-file-list="false"
            accept=".xls,.xlsx"
            :on-change="excleUpload"
          >
            <el-button size="mini" type="text">卖点导入</el-button>
          </el-upload>
        </h2>
        <el-form-item label="是否带赠品" :prop="`sellPoints[${index}].giveawayFlag`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-select v-model="formDate.sellPoints[index].giveawayFlag" :disabled="isDisabled" placeholder="请选择" clearable>
            <el-option
              v-for="item in giveawayFlag"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-popover placement="bottom" trigger="click">
            <gift />
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-form-item v-show="formDate.sellPoints[index].giveawayFlag == 1" label="赠品失效日期" :prop="`sellPoints[${index}].giveawayExpiryDate`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-date-picker
            v-model="formDate.sellPoints[index].giveawayExpiryDate"
            clearable
            :disabled="isDisabled"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item label="搜索词" :prop="`sellPoints[${index}].keywords`" :rules="{required: true, validator:validator, trigger: 'change'}">
          <el-input
            v-model.trim="formDate.sellPoints[index].keywords"
            :disabled="isDisabled"
            placeholder="请输入"
            type="textarea"
            maxlength="64"
            show-word-limit
            :rows="2"
            clearable
          />
          <el-popover placement="bottom" trigger="click">
            <searchTerm />
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-form-item label="运输方式" :prop="`sellPoints[${index}].transportMode`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-select v-model="formDate.sellPoints[index].transportMode" :disabled="isDisabled" placeholder="请选择" clearable>
            <el-option
              v-for="item in transportMode"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-popover placement="bottom" trigger="click">
            <transport />
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-form-item label="商品基本信息" :prop="`sellPoints[${index}].baseInfoDesc`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-input
            v-model="formDate.sellPoints[index].baseInfoDesc"
            :disabled="isDisabled"
            placeholder="请输入"
            type="textarea"
            maxlength="64"
            show-word-limit
            :rows="2"
            clearable
          />
          <el-popover placement="bottom" trigger="click">
            请完整填写商品的卖点信息，作为文描服务商制作详情页的素材内容参考使用
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-form-item label="生产商信息" :prop="`sellPoints[${index}].productiveProcessDesc`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-input
            v-model="formDate.sellPoints[index].productiveProcessDesc"
            :disabled="isDisabled"
            placeholder="请输入"
            type="textarea"
            maxlength="64"
            show-word-limit
            :rows="2"
            clearable
          />
          <el-popover placement="bottom" trigger="click">
            请围绕商品的产地/养殖过程特色等进行故事性诉说（若无则填写“无”）
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-form-item label="头图卖点" :prop="`sellPoints[${index}].adword`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-input
            v-model="formDate.sellPoints[index].adword"
            :disabled="isDisabled"
            placeholder="请输入"
            type="textarea"
            maxlength="100"
            show-word-limit
            :rows="2"
            clearable
          />
          <el-popover placement="bottom" trigger="click">
            一句吸睛广告语，即突出唯一销售卖点，用于详情页头图海报，
            <br>
            例如：新西兰进口乳粉，富含乳酸菌
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-form-item label="商品展示" :prop="`sellPoints[${index}].displayDesc`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-input
            v-model="formDate.sellPoints[index].displayDesc"
            :disabled="isDisabled"
            placeholder="请输入"
            type="textarea"
            maxlength="200"
            show-word-limit
            :rows="2"
            clearable
          />
          <el-popover placement="bottom" trigger="click">
            请用2-3段文案描述商品外观及功效，例如：
            <br>
            1.小巧便捷  瓶身小巧，随身携带，可以随时与亲朋好友分享
            <br>
            2.营养健康  乳酸菌中以嗜酸杆菌和双歧杆菌对人体的影响更显著
            <br>
            3.方便引用  每排内置包装吸管，方便饮用
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-form-item label="温馨提示" :prop="`sellPoints[${index}].buyinTips`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-input
            v-model="formDate.sellPoints[index].buyinTips"
            :disabled="isDisabled"
            placeholder="请输入"
            type="textarea"
            maxlength="200"
            show-word-limit
            :rows="2"
            clearable
          />
          <el-popover placement="bottom" trigger="click">
            请用2-3段文案描述商品的温馨提示，例如：
            <br>
            1.注意事项
            <br>
            2.食用方法/使用方法
            <br>
            3.2-3种经典做法（鲜食类）
            <br>
            4.家中常备、送礼、老人小孩均可使用等使用场景。
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <special :is-disabled="isDisabled" :goods-info="formDate.sellPoints[index]" />

        <el-form-item label="品牌介绍">
          <el-input
            v-model="formDate.sellPoints[index].brandIntroduction"
            :disabled="isDisabled"
            placeholder="请输入"
            type="textarea"
            maxlength="64"
            show-word-limit
            :rows="2"
            clearable
          />
          <el-popover placement="bottom" trigger="click">
            从品牌的立意、诉求、涵盖品类等方面对品牌进行详细描述。
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-form-item label="商品特色" :prop="`sellPoints[${index}].feature`" :rules="{ required: true, message: ' ', trigger: 'change' }">
          <el-input
            v-model="formDate.sellPoints[index].feature"
            :disabled="isDisabled"
            placeholder="请输入"
            type="textarea"
            maxlength="200"
            show-word-limit
            :rows="2"
            clearable
          />
          <el-popover placement="bottom" trigger="click">
            请围绕商品核心特性（2~3个）进行详细描述，例如：
            <br>
            1.新西兰进口乳粉  选用新西兰进口乳粉，用料讲究，奶源品质更标准。
            <br>
            2.充分发酵  坚持36小时发酵时间，发酵考究，口感浓郁香甜。
            <i slot="reference" class="el-icon-question" />
          </el-popover>
        </el-form-item>

        <el-row>
          <el-form-item label="商品特色佐证">
            <div class="uploadPhoto">
              <div v-for="(img, i) in formDate.sellPoints[index].sellPointVoucherUrl" :key="i" class="elImg">
                <el-image :src="img.resourceUrl | transImgUrl" :preview-src-list="formDate.sellPoints[index].sellPointVoucherUrl | transUrlName" />
                <div v-if="!isDisabled" class="del" @click="delImg(img,formDate.sellPoints[index].sellPointVoucherUrl)">
                  <i class="el-icon-delete" />
                </div>
              </div>
              <el-upload
                v-if="!isDisabled"
                :auto-upload="false"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                multiple
                accept=".png,.jpg,.jpeg"
                :on-change="(file,fileList)=>{
                  handleOnChange(file,formDate.sellPoints[index].sellPointVoucherUrl,formDate.sellPoints[index].id,3)
                }"
              >
                <i class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <el-popover placement="bottom" trigger="click" width="400">
                所有录入的商品信息，必须与商品客观事实一致同时需有图片作为佐证，
                以商品包装印刷字样为优先佐证，
                以厂商或沃尔玛官方工作人员邮件信息截图为次要佐证。
                佐证图会同步到素材图供审核使用。
                <i slot="reference" class="el-icon-question" />
              </el-popover>
            </div>

          </el-form-item>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import moment from 'moment'
import { transportType } from '@/views/coi/commonJs/dictionary'
import { exportExcel, uploadExcel, uploadFile, delFile } from '@/api/coi/onlineTaskAPI/sku'
import transport from './fieldPrompt/transport'
import searchTerm from './fieldPrompt/searchTerm'
import gift from './fieldPrompt/gift'
import special from '@/views/coi/making/special.vue'
import bus from '@/utils/eventBus.js'
import { authentication } from '@/utils/processingData.js'

export default {
  name: 'SellPoints',
  components: { transport, searchTerm, gift, special },
  filters: {
    transUrlName(imgArr) {
      return imgArr.map((e) => authentication(e.resourceUrl))
    },
    transImgUrl(url) {
      return authentication(url)
    }
  },
  props: {
    formDate: {
      type: Object,
      default: () => {
        return {
          sellPoints: []
        }
      }
    },
    isDisabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      giveawayFlag: [{ value: 1, label: '是' }, { value: 0, label: '否' }],
      transportMode: transportType,
      pickerOptions: {
        disabledDate(time) {
          // 8.64e7
          //  return time.getTime() < Date.now() - 8.64e7; //只能选择今天及今天之后
          // return time.getTime() > Date.now() - 8.64e7; //只能选择今天之前，连今天都不能选
          return time.getTime() < Date.now() - 8.64e6 // 只能选择今天之后，连今天都不能选
          // return time.getTime() > Date.now() - 8.64e6; //只能选择今天及今天之前
        }
      },
      validator: (rule, value, callback) => {
        if (!value) callback(new Error('请输入搜索词'))
        else if (this.getCharCount(value, ',') > 4 || this.getCharCount(value, '，') > 4) callback(new Error('搜索词最多可编辑5个'))
        else callback()
      },
      batchNum: 0
    }
  },
  methods: {
    getCharCount(str, char) {
      var regex = new RegExp(char, 'g')
      var result = str.match(regex)
      var count = !result ? 0 : result.length
      return count
    },
    async exportExcel() {
      try {
        bus.$emit('loadingChange', true)
        const idArr = this.formDate.sellPoints.map((item) => item.id)
        const date = +new Date()
        const fileName = `商品卖点维护 ${moment(date).format('YYYY-MM-DD')}`
        await exportExcel(idArr, fileName)
      } finally {
        bus.$emit('loadingChange', false)
      }
    },
    async excleUpload(file) {
      try {
        if (file.raw.type !== 'application/vnd.ms-excel') return this.$message({ message: '上传文件格式错误!', type: 'error' })
        const formData = new FormData()
        formData.append('file', file.raw)
        bus.$emit('loadingChange', true)
        const { result } = await uploadExcel(formData)
        if (Array.isArray(result)) {
          this.$message({
            type: 'success',
            message: '导入成功'
          })
          result.forEach((item) => {
            const index = this.formDate.sellPoints.findIndex((e) => e.id === item.id)
            if (index !== -1) this.$set(this.formDate.sellPoints, index, item)
          })
        }
      } finally {
        bus.$emit('loadingChange', false)
      }
    },
    change(data) {
      data.giveawayExpiryDate = null
    },
    // 删除佐证
    delImg(img, imgList) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { result } = await delFile(img)
        if (result) {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          const index = imgList.findIndex((item) => item === img)
          imgList.splice(index, 1)
        } else {
          this.$message({
            message: '删除失败,请稍后重试!',
            type: 'error'
          })
        }
      }).catch(() => {})
    },
    handleOnChange(file, urlList, id, type) {
      var size = file.size / 1024 / 1024
      if (size > 3) {
        this.$message({
          showClose: true,
          message: '图片大小必须小于3M',
          type: 'error'
        })
        return
      }
      this.upload(file, urlList, id, type)
    },
    // 上传文件至服务器
    async upload(file, urlList, id, type) {
      try {
        this.batchNum++
        bus.$emit('loadingChange', true)
        const formData = new FormData()
        formData.append('file', file.raw)
        formData.append('skuId', id)
        formData.append('type', type)
        const result = await uploadFile(formData)
        if (result.code === '0') {
          urlList.push(result.result)
        }
      } finally {
        this.batchNum--
        if (this.batchNum === 0) bus.$emit('loadingChange', false)
      }
    },
    // Remove the rules
    removeRules() {
      this.$refs.ruleForm.resetFields()
      this.tipShow = false
    }
  }
}
</script>

<style scoped lang="scss">
.sellPoints{
  .tip{
    color: #aaa;
    font-size: 14px;
  }
  .goodsList{
    border-bottom: dashed #ccc 1px;
    &:last-child{
      border-bottom: none;
    }
    &:nth-child(n+2){
      margin-top: 10px;
    }
    h2{
      font-size: 14px;
      height: 40px;
      display: flex;
      align-items: center;
      span{
        margin-right: 20px;
      }
    }
  }
}
/deep/ .el-input,
/deep/ .el-textarea{
  width: 200px;
}
/deep/ .el-form-item{
  margin-right: 10px;
}

// 上传佐证样式
.uploadPhoto {
  min-height: 100px;
  display: flex;
  flex-wrap: wrap;
  .elImg {
    height: 100px;
    width: 100px;
    display: inline-block;
    margin-right: 10px !important;
    margin-bottom: 10px !important;
    position: relative;
    &:hover .del {
      display: block;
      transition: all 1s linear;
      height: 15px;
    }
    .del {
      line-height: 15px;
      border-radius: 1px;
      padding: 2px 0;
      text-align: center;
      display: none;
      width: 100%;
      height: 0;
      overflow: hidden;
      position: absolute;
      left: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      cursor: pointer;
      color: #fff;
      font-size: 14px;
    }
    /deep/ .el-image {
      border-radius: 5px;
      height: 100%;
      width: 100%;
    }
  }
}

.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader /deep/.el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
i.el-icon-question{
  vertical-align: middle;
  margin-left: 10px;
  cursor: pointer;
  font-size: 16px;
}
</style>
